package ee.ut.cs.mc.madp.p2pdivider.fragment;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import ee.ut.cs.mc.madp.p2pdivider.R;
import ee.ut.cs.mc.madp.p2pdivider.Utils;

/**
 * Fragment for media chooser
 * 
 * @author Tambet Artma
 */
public class MediaFragment extends Fragment {

    private View view;
    // Stores names of traversed directories
    private final ArrayList<File> selectedFiles = new ArrayList<File>();
    FileTreeGridAdapter gridAdapter = null;

    public ArrayList<File> getSelectedFiles() {
        return selectedFiles;
    }

    private static final String TAG = "F_PATH";

    private Item[] fileList;
    private final File imagepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    private final File videopath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);

    ListAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_media, null);
        Log.e(TAG, Arrays.deepToString(fileList));
        loadFileList();
        Log.e(TAG, Arrays.deepToString(fileList));
        ListView list = (ListView) view.findViewById(R.id.fileTree);
        list.setAdapter(new FileTreeListAdapter(getActivity(), R.layout.view_file_tree_list_row, fileList));

        GridView grid = (GridView) view.findViewById(R.id.selectedFiles);
        gridAdapter = new FileTreeGridAdapter(getActivity(), R.layout.view_file_tree_grid_cell, new File[] {});
        grid.setAdapter(gridAdapter);
        return view;
    }

    // -----------------------------------

    private class FileTreeListAdapter extends ArrayAdapter<Item> {

        private final Item[] files;

        public FileTreeListAdapter(Context context, int textViewResourceId, Item[] objects) {
            super(context, textViewResourceId, objects);
            files = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                Log.e(TAG, "V was null");
                LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.view_file_tree_list_row, null);
            }
            final Item file = getItem(position);
            if (file != null) {
                CheckBox checkBox = (CheckBox) v.findViewById(R.id.fileTreeListCheckbox);

                if (checkBox != null) {
                    checkBox.setText(file.file);
                    checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            File fFile = new File(file.folder, file.file);
                            if (isChecked) {
                                selectedFiles.add(fFile);
                                gridAdapter.add(fFile);
                            } else {
                                selectedFiles.add(fFile);
                                gridAdapter.remove(fFile);
                            }
                        }
                    });
                }
            }

            return v;
        }

    }

    public class FileTreeGridAdapter extends ArrayAdapter<File> {

        public FileTreeGridAdapter(Context context, int textViewResourceId, File[] files) {
            super(context, textViewResourceId, new ArrayList<File>(Arrays.asList(files)));
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.view_file_tree_grid_cell, null);
            }
            final File file = getItem(position);
            TextView text = (TextView) v.findViewById(R.id.fileTreeCellName);
            ImageView image = (ImageView) v.findViewById(R.id.fileTreeCellImage);

            if (file != null) {
                v.setVisibility(View.VISIBLE);
                text.setText(file.getName());

                Bitmap decodedBitmap = Utils.decodeSampledBitmapFromResource(file, 80, 120);
                image.setImageBitmap(decodedBitmap);

                image.setVisibility(View.VISIBLE);
            } else {
                v.setVisibility(View.INVISIBLE);
            }

            return v;
        }
    }

    // --------------------------------------

    private void loadFileList() {
        try {
            imagepath.mkdirs();
            videopath.mkdirs();
        } catch (SecurityException e) {
            Log.e(TAG, "unable to write on the sd card ");
        }

        // Checks whether path exists
        if (imagepath.exists() || videopath.mkdirs()) {
            FilenameFilter filter = new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    // Filters based on whether the file is hidden or not
                    return (sel.isFile() || sel.isDirectory())
                            && !sel.isHidden();
                }
            };

            String[] fimageList = imagepath.list(filter);
            String[] fvideoList = videopath.list(filter);

            fileList = new Item[fimageList.length + fvideoList.length];

            for (int i = 0; i < fileList.length; i++) {

                if (i < fimageList.length) {
                    fileList[i] = new Item(imagepath, fimageList[i], R.drawable.file_icon);

                    // Convert into file path
                    File sel = new File(imagepath, fimageList[i]);

                    // Set drawables
                    if (sel.isDirectory()) {
                        fileList[i].icon = R.drawable.directory_icon;
                        Log.d("DIRECTORY", fileList[i].file);
                    } else {
                        Log.d("FILE", fileList[i].file);
                    }
                }
                if (i >= fimageList.length) {
                    fileList[i] = new Item(videopath, fvideoList[i - fimageList.length], R.drawable.file_icon);

                    // Convert into file path
                    File sel = new File(videopath, fvideoList[i - fimageList.length]);

                    // Set drawables
                    if (sel.isDirectory()) {
                        fileList[i].icon = R.drawable.directory_icon;
                        Log.d("DIRECTORY", fileList[i].file);
                    } else {
                        Log.d("FILE", fileList[i].file);
                    }
                }
            }
        } else {
            throw new RuntimeException("Hjeloouuuu.");
        }
    }

    private class Item {
        public File folder;
        public String file;
        public int icon;

        public Item(File folder, String file, Integer icon) {
            this.folder = folder;
            this.file = file;
            this.icon = icon;
        }

        @Override
        public String toString() {
            return file;
        }
    }
}
